package com.zmn.plat.admin.controller.supplier;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dto.ResultDTO;
import com.zmn.common.dto.StatusDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.plat.model.entity.company.BaseCompany;
import com.zmn.plat.model.entity.supplier.ScmSupplier;
import com.zmn.plat.model.entity.supplier.ScmSupplierDTO;

/**
 * @author DaiZhichao
 * @version v1.0
 * @since 2019/2/1 15:38 类说明：如果有特殊说明加上这一行
 */
@RestController
@RequestMapping("/supplier/ajax")
public class ScmSupplierModifyController extends ScmSupplierBaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 描述: [Ajax] 更改供应商可用状态
     *
     * @author DaiZhichao
     * @since 2018/11/6 20:59
     */
    @RequestMapping(value = "/updateStatus", produces = "application/json; charset=utf-8")
    @RequiresPermissions("/supplier/ajax/updateStatus.action")
    public ResultDTO updateStatus(@RequestParam(value = "ids[]", defaultValue = "") ArrayList<Integer> ids,
        @RequestParam(value = "status", defaultValue = "0") int status) {
        if (ids.isEmpty()) {
            return new ResultDTO(StatusConsts.STATUS_ERROR, "ERROR", false, "请选择要更改状态的供应商！");
        }

        StatusDTO statusDTO = new StatusDTO();
        statusDTO.setIds(ids);
        statusDTO.setStatus(status);
        statusDTO.setUpdater(getMcStaff().getRealName());
        statusDTO.setUpdateTime(DateUtil.getNow());
        scmSupplierService.updateStatusBatch(statusDTO);

        return new ResultDTO(StatusConsts.STATUS_SUCCESS, "OK", true, "操作成功！");
    }

    /**
     * 描述: [Ajax] 添加/修改供应商信息
     *
     * @author DaiZhichao
     * @since 2018/11/6 20:59
     */
    @RequestMapping(value = "/addEdit", produces = "application/json; charset=utf-8")
    @RequiresPermissions("/supplier/ajax/addEdit.action")
    public ResultDTO addEdit(@RequestBody ScmSupplierDTO supplierDTO) {
        List<Integer> pertainCompanyIds = supplierDTO.getPertainCompanyIds();
        ScmSupplier supplier = supplierDTO.getSupplier();

        String lable = null;

        if (isDuplicateSupplier(supplier)) {
            return ResultDTO.resultError("供应商名称重复");
        }

        BaseCompany byKey = companyService.findByKey(supplier.getCompanyId());
        if (byKey == null) {
            return ResultDTO.resultError("选择所属公司不存在！");
        }
        if (StringUtil.isBlank(byKey.getBankName()) || StringUtil.isBlank(byKey.getBankCardName())
            || StringUtil.isBlank(byKey.getBankCardNo())) {
            return ResultDTO.resultError("请完善所属公司对应银行卡信息！");
        }

        LoginStaff mcStaff = getMcStaff();
        supplier.setUpdater(mcStaff.getRealName());
        pertainCompanyIds = pertainCompanyIds.stream().distinct().collect(Collectors.toList());
        try {
            if (Objects.isNull(supplier.getSupplierId())) {
                scmSupplierBService.insert(supplier, pertainCompanyIds);
                lable = "新增供应商";
            } else {
                scmSupplierBService.updateByKey(supplier, pertainCompanyIds);
                lable = "修改供应商";
            }

            return ResultDTO.resultSuccess(String.format("%s成功！", lable));
        } catch (Exception ex) {
            logger.error("新增/修改供应商失败", ex);
            return ResultDTO.resultError(String.format("%s失败！", lable));
        }
    }

    /**
     * 描述: 判断重复供应商
     *
     * @author DaiZhichao
     * @since 2018/11/6 20:59
     */
    private boolean isDuplicateSupplier(ScmSupplier supplier) {
        if (Objects.isNull(supplier)) {
            return false;
        }

        Integer num = scmSupplierService.isDuplicate(supplier.getName());

        return Objects.isNull(supplier.getSupplierId()) ? num > 0 : num > 1;
    }
}
